package cn.easyutil.project.web.handler;

import cn.easyutil.util.javaUtil.LoggerUtil;
import cn.easyutil.project.web.advice.RequestBeforeAdvice;
import cn.easyutil.project.web.util.RequestPool;
import cn.easyutil.project.web.util.SpringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Component
public class RequestBeforeHandler implements HandlerInterceptor {

    @Autowired(required = false)
    private RequestBeforeAdvice requestBeforeAdvice;

    /**
     * 访问接口之前执行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Method method = null;
        Class<?> controllerClass = null;
        if(handler instanceof HandlerMethod){
            HandlerMethod hm = (HandlerMethod) handler;
            method = hm.getMethod();
            controllerClass = method.getDeclaringClass();
        }
        if(requestBeforeAdvice == null){
            RequestBeforeAdvice bean = SpringUtil.getBean(RequestBeforeAdvice.class);
            if(bean == null){
                requestBeforeAdvice = new DefaultRequestBeforeAdvice();
            }else{
                requestBeforeAdvice = bean;
            }
        }
        //续租用户登陆token
        RequestPool.refranshToken();
        LoggerUtil.info(this.getClass(),"==> sessionId : " + RequestPool.get().getSession().getId());
        return requestBeforeAdvice.process(request,response,method,controllerClass);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除掉保存的当前登陆用户的Token
    }
}
